package keyboard.interceptor;

import keyboaUtil.userData.MyCookie;
import keyboard.entity.User;
import keyboard.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 2B键盘
 * @create 2018-04-20 16:30
 * @desc 是否登陆
 **/
public class IsLogin implements HandlerInterceptor {

    private String identity;
    private String password;

    @Autowired
    UserService service;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //初始化
        this.identity = null;
        this.password = null;
        HttpSession session = request.getSession();
        /**
         * 拿到cookie中的数据
         */
        Cookie[] cookies = request.getCookies();
        for(int i=0; i<cookies.length; i++){
           if(cookies[i].getName().equals(MyCookie.KEYBOARD_IDENTITY) ||
                   cookies[i].getName() == MyCookie.KEYBOARD_IDENTITY){
                this.identity = cookies[i].getValue();
               System.out.println("COOKIE: "+cookies[i].getName()+"------------>"+cookies[i].getValue());
           }
            if(cookies[i].getName().equals(MyCookie.KEYBOARD_PASSWORD) ||
                    cookies[i].getName() == MyCookie.KEYBOARD_PASSWORD){
                this.password = cookies[i].getValue();
                System.out.println("COOKIE: "+cookies[i].getName()+"------------>"+cookies[i].getValue());
            }
        }
        /**
         * 判断是否登陆
         */
        User user = new User();
        user.setIdentity(this.identity);
        user.setPassword(this.password);
        user = service.login(user);
        if(user==null){
            System.out.println("未登录------");
            response.sendRedirect(request.getContextPath()+"/views/login/index.jsp");
            return false;
        }else{
            System.out.println("已登录!");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
